#!/bin/bash

# EmailQA System Test Script
# Usage: ./test.sh [development|testing|production]

set -e

ENVIRONMENT=${1:-development}

echo "🧪 Testing EmailQA system in $ENVIRONMENT mode..."

# API Endpoints
API_BASE="http://localhost:5000"
HEALTH_ENDPOINT="$API_BASE/api/health"
EMAILQA_ENDPOINT="$API_BASE/api/emailqa"
CREATE_ENDPOINT="$API_BASE/api/emailqa/create"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Test function
test_endpoint() {
    local name=$1
    local endpoint=$2
    local expected_code=$3
    local data=$4
    
    echo -n "🔍 Testing $name... "
    
    if [ -n "$data" ]; then
        response=$(curl -s -w "%{http_code}" -X POST -H "Content-Type: application/json" -d "$data" "$endpoint")
    else
        response=$(curl -s -w "%{http_code}" "$endpoint")
    fi
    
    http_code="${response: -3}"
    body="${response%???}"
    
    if [ "$http_code" -eq "$expected_code" ]; then
        echo -e "${GREEN}✅ PASSED${NC} ($http_code)"
        return 0
    else
        echo -e "${RED}❌ FAILED${NC} ($http_code, expected $expected_code)"
        echo "Response: $body"
        return 1
    fi
}

# Health Check
echo "🏥 Testing Health Check..."
test_endpoint "Health Check" "$HEALTH_ENDPOINT" 200

# EmailQA Query Test
echo "📧 Testing EmailQA Query..."
query_data='{"content_list": ["abc.task_id=1", "def.task_id=2"]}'
test_endpoint "EmailQA Query" "$EMAILQA_ENDPOINT" 200 "$query_data"

# EmailQA Creation Test
echo "📧 Testing EmailQA Creation..."
create_data='{
    "system_conversation_id": "test_docker_001",
    "q_body": "Docker test question",
    "q_subject": "Docker test subject",
    "q_real_question": "Docker test real question",
    "q_question_subject": "Docker test question subject",
    "customer_service_answer": "Hi TEAM, this is a docker test"
}'
test_endpoint "EmailQA Creation" "$CREATE_ENDPOINT" 201 "$create_data"

# Test invalid data
echo "📧 Testing Invalid EmailQA Creation..."
invalid_data='{"system_conversation_id": "test"}'
test_endpoint "Invalid EmailQA Creation" "$CREATE_ENDPOINT" 400 "$invalid_data"

# Test MCP Tool (if in development mode)
if [ "$ENVIRONMENT" != "production" ]; then
    echo "🔧 Testing MCP Tool..."
    # This would require MCP client setup, so we'll just check if the container is running
    if docker-compose ps mcp-server | grep -q "Up"; then
        echo -e "${GREEN}✅ MCP Server is running${NC}"
    else
        echo -e "${YELLOW}⚠️  MCP Server is not running${NC}"
    fi
fi

echo ""
echo -e "${GREEN}🎉 All tests passed!${NC}"
echo "📊 API Documentation: $API_BASE/docs/"
echo "🔗 Health Check: $HEALTH_ENDPOINT"